import 'dart:io' as io;
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:lx_widgets_library/enum/permission_enum.dart';
import 'package:lx_widgets_library/utils/share_preferences_util.dart';
import 'package:permission_handler/permission_handler.dart';

// ignore: constant_identifier_names
const String PERMISSION_PERMANENTLY_DENIED_LIST =
    "PERMISSION_PERMANENTLY_DENIED_LIST";

// 系统权限管理
class SystemPermissionUtil {
  /// 正在请求的权限（防止同时重复请求报错）
  static List<Permission> _requestingPermissions = [];

  ///
  /// 申请蓝牙权限
  ///
  static void requestBluetoothPermission({
    void Function()? onSuccess,
    void Function()? onCancel,
    void Function(Permission? permission)? onFailed,
  }) async {
    if (io.Platform.isAndroid) {
      _requestingPermissions = [
        Permission.bluetoothScan,
        Permission.bluetoothConnect,
        Permission.locationWhenInUse,
      ];
    } else {
      _requestingPermissions = [Permission.bluetooth];
    }
    requestPermissions(
      _convertPermissions(_requestingPermissions),
      onSuccess: onSuccess,
      onCancel: onCancel,
      onFailed: onFailed,
    );
  }

  ///
  /// 申请相册权限
  ///
  static void requestAlbumPermission({
    void Function()? onSuccess,
    void Function()? onCancel,
    void Function(Permission? permission)? onFailed,
  }) async {
    if (io.Platform.isAndroid) {
      var info = await DeviceInfoPlugin().androidInfo;
      if (info.version.sdkInt != null && info.version.sdkInt! >= 33) {
        // Android 13 and above
        _requestingPermissions = [
          Permission.photos,
          Permission.videos,
        ];
      } else {
        _requestingPermissions = [
          Permission.storage,
        ];
      }
    } else {
      _requestingPermissions = [Permission.storage];
    }
    requestPermissions(
      _convertPermissions(_requestingPermissions),
      onSuccess: onSuccess,
      onCancel: onCancel,
      onFailed: onFailed,
    );
  }

  /// 申请读取本地录音文件
  static void requestAudioFilePermission({
    void Function()? onSuccess,
    void Function()? onCancel,
    void Function(Permission? permission)? onFailed,
  }) async {
    if (io.Platform.isAndroid) {
      var info = await DeviceInfoPlugin().androidInfo;
      if (info.version.sdkInt != null && info.version.sdkInt! >= 33) {
        // Android 13 and above
        _requestingPermissions = [
          Permission.audio,
        ];
      } else {
        _requestingPermissions = [
          Permission.storage,
        ];
      }
    } else {
      _requestingPermissions = [Permission.storage];
    }
    requestPermissions(
      _convertPermissions(_requestingPermissions),
      onSuccess: onSuccess,
      onCancel: onCancel,
      onFailed: onFailed,
    );
  }

  ///
  /// 同时申请多个权限
  /// onSuccess: 所有权限申请成功
  /// onCancel: 在权限说明弹框中点击了取消申请
  /// onFailed: 存在被拒绝的权限（只返回第一个）
  ///
  static void requestPermissions(
    List<CustomPermissions> permissions, {
    void Function()? onSuccess,
    void Function()? onCancel,
    void Function(Permission permission)? onFailed,
  }) async {
    debugPrint('requestPermission: $permissions');
    // 请求授权的权限列表（排除已授权的权限）
    List<Permission> requestPermissions = [];
    // 不再提醒的被拒绝权限列表
    List<Permission> notRequestPermissions = [];
    // 永久拒绝的权限列表
    List<String> permanentlyDeniedList = SharedPreferencesService.to
            .getStringList(PERMISSION_PERMANENTLY_DENIED_LIST) ??
        [];
    for (var i = 0; i < permissions.length; i++) {
      Permission permission = _convertPermission(permissions[i]);
      PermissionStatus status = await permission.status;
      if (!status.isGranted) {
        if (status == PermissionStatus.permanentlyDenied ||
            permanentlyDeniedList.contains(permission.value.toString())) {
          // 永久拒绝（被拒绝且不再提示）
          notRequestPermissions.add(permission);
        } else {
          // 权限可请求
          requestPermissions.add(permission);
        }
      }
    }
    if (requestPermissions.isEmpty) {
      _requestingPermissions.clear();
      if (notRequestPermissions.isNotEmpty) {
        // 永久拒绝
        if (onFailed != null) onFailed(notRequestPermissions.first);
      } else {
        // 所有权限都已经授权
        if (onSuccess != null) onSuccess();
      }
    } else {
      // 未授权，发起一次申请
      debugPrint('requestPermission: $requestPermissions 未授权 发起申请');
      requestPermissions.request().then((statuses) {
        debugPrint('requestPermission: 授权结果 $statuses');
        _requestingPermissions.clear();
        // 授权被拒绝的权限列表
        List<Permission> deniedPermissions = [];
        for (var i = 0; i < requestPermissions.length; i++) {
          Permission permission = requestPermissions[i];
          PermissionStatus? status = statuses[permission];
          if (status != PermissionStatus.granted) {
            deniedPermissions.add(permission);
          }

          if (status == PermissionStatus.permanentlyDenied &&
              !permanentlyDeniedList.contains(permission.value.toString())) {
            // 被永久拒绝后，如果本地没有记录，则添加至本地列表
            permanentlyDeniedList.add(permission.value.toString());
            SharedPreferencesService.to.setStringList(
                PERMISSION_PERMANENTLY_DENIED_LIST, permanentlyDeniedList);
          }
          if (status == PermissionStatus.granted &&
              permanentlyDeniedList.contains(permission.value.toString())) {
            // 被授权后，如果本地有永久拒绝记录，则删除该条记录
            permanentlyDeniedList.remove(permission.value.toString());
            SharedPreferencesService.to.setStringList(
                PERMISSION_PERMANENTLY_DENIED_LIST, permanentlyDeniedList);
          }
        }

        if (deniedPermissions.isEmpty) {
          if (notRequestPermissions.isNotEmpty) {
            // 存在永久拒绝的权限
            if (onFailed != null) onFailed(notRequestPermissions.first);
          } else {
            // 所有权限都已经授权
            if (onSuccess != null) onSuccess();
          }
        } else {
          // 授权失败（存在被拒绝的权限，只返回第一个）
          if (onFailed != null) onFailed(deniedPermissions.first);
        }
      }).catchError((error) {
        debugPrint('error:$error');
      });
    }
  }

  // permissions转CustomPermissions
  static List<CustomPermissions> _convertPermissions(
      List<Permission> permissions) {
    List<CustomPermissions> customPermissions = [];
    for (var permission in permissions) {
      if (permission == Permission.storage) {
        customPermissions.add(CustomPermissions.storage);
      } else if (permission == Permission.camera) {
        customPermissions.add(CustomPermissions.camera);
      } else if (permission == Permission.photos) {
        customPermissions.add(CustomPermissions.photos);
      } else if (permission == Permission.videos) {
        customPermissions.add(CustomPermissions.videos);
      } else if (permission == Permission.audio) {
        customPermissions.add(CustomPermissions.audio);
      } else if (permission == Permission.location) {
        customPermissions.add(CustomPermissions.location);
      } else if (permission == Permission.bluetooth) {
        customPermissions.add(CustomPermissions.bluetooth);
      } else if (permission == Permission.bluetoothScan) {
        customPermissions.add(CustomPermissions.bluetoothScan);
      } else if (permission == Permission.bluetoothConnect) {
        customPermissions.add(CustomPermissions.bluetoothConnect);
      } else if (permission == Permission.locationWhenInUse) {
        customPermissions.add(CustomPermissions.locationWhenInUse);
      }
    }
    return customPermissions;
  }

  // CustomPermission转Permission
  static Permission _convertPermission(CustomPermissions permission) {
    switch (permission) {
      case CustomPermissions.storage:
        return Permission.storage;
      case CustomPermissions.camera:
        return Permission.camera;
      case CustomPermissions.photos:
        return Permission.photos;
      case CustomPermissions.videos:
        return Permission.videos;
      case CustomPermissions.audio:
        return Permission.audio;
      case CustomPermissions.location:
        return Permission.location;
      case CustomPermissions.bluetooth:
        return Permission.bluetooth;
      case CustomPermissions.bluetoothScan:
        return Permission.bluetoothScan;
      case CustomPermissions.bluetoothConnect:
        return Permission.bluetoothConnect;
      case CustomPermissions.locationWhenInUse:
        return Permission.locationWhenInUse;
    }
  }
}
